<template>
  <div class="carousel-edit">
    <div class="page-header">
      <h2>编辑轮播图</h2>
      <p>修改轮播图内容信息</p>
    </div>

    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
        class="carousel-form"
        label-position="left"
        size="large"
        v-loading="loading"
      >
        <el-form-item label="轮播图标题" prop="title" required>
          <el-input
            v-model="formData.title"
            placeholder="请输入..."
            maxlength="50"
            show-word-limit
            style="width: 400px"
          />
        </el-form-item>
        
        <el-form-item label="轮播图" prop="imageUrl" required>
          <div class="upload-section">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              accept="image/*"
              drag
            >
              <div class="uploaded-container" v-if="formData.imageUrl">
                <img :src="formData.imageUrl" class="uploaded-image" />
                <div class="image-overlay">
                  <el-icon class="delete-icon" @click.stop="removeImage">
                    <Close />
                  </el-icon>
                </div>
              </div>
              <div v-else class="upload-area">
                <el-icon class="upload-icon"><Plus /></el-icon>
              </div>
            </el-upload>
            <div class="upload-hint">
              建议尺寸375*240，不要超过1M
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="轮播图状态" prop="isEnabled" required>
          <el-switch
            v-model="formData.isEnabled"
            size="large"
            :active-value="true"
            :inactive-value="false"
            active-color="#409EFF"
          />
        </el-form-item>
        
        <el-form-item label="轮播图链接地址" prop="linkUrl" required>
          <el-input
            v-model="formData.linkUrl"
            placeholder="请输入..."
            style="width: 400px"
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="sortOrder" required>
          <div class="sort-section">
            <el-input-number
              v-model="formData.sortOrder"
              :min="1"
              :max="999"
              placeholder="请输入..."
              style="width: 400px"
              controls-position="right"
            />
            <div class="sort-hint">
              填写数字，数字越大越靠前
            </div>
          </div>
        </el-form-item>


      </el-form>

      <div class="form-actions">
        <el-button size="large" @click="handleCancel">取消</el-button>
        <el-button type="primary" size="large" @click="handleSubmit" :loading="submitLoading">
          提交
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { carouselApi } from '@/api/index'
import type { CarouselItem } from '@/api/index'
import { Plus, Close } from '@element-plus/icons-vue'

/**
 * 轮播图编辑页面
 * 支持数据回填和更新功能
 */

const router = useRouter()
const route = useRoute()
const formRef = ref()
const loading = ref(false)
const submitLoading = ref(false)

// 表单数据接口
interface FormData {
  id?: number
  title: string
  imageUrl: string
  isEnabled: boolean
  linkUrl: string
  sortOrder: number
}

// 表单数据
const formData = reactive<FormData>({
  title: '',
  imageUrl: '',
  isEnabled: true,
  linkUrl: '',
  sortOrder: 1
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入轮播图标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请上传轮播图片', trigger: 'change' }
  ],
  linkUrl: [
    { required: true, message: '请输入链接地址', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序序号', trigger: 'blur' }
  ],
  isEnabled: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],

}

// 模拟轮播图数据
const mockCarouselData = {
  1: {
    id: 1,
    title: 'banner',
    imageUrl: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?ixlib=rb-4.0.3&auto=format&fit=crop&w=375&q=80',
    isEnabled: true,
    linkUrl: 'https://example.com/health-check',
    sortOrder: 1
  },
  2: {
    id: 2,
    title: '在线问诊服务',
    imageUrl: 'https://images.unsplash.com/photo-1576091160399-112ba8d25d1f?ixlib=rb-4.0.3&auto=format&fit=crop&w=375&q=80',
    isEnabled: true,
    linkUrl: 'https://example.com/consultation',
    sortOrder: 2
  },
  3: {
    id: 3,
    title: '医院导航系统',
    imageUrl: 'https://images.unsplash.com/photo-1666214280557-f1b5022eb634?ixlib=rb-4.0.3&auto=format&fit=crop&w=375&q=80',
    isEnabled: false,
    linkUrl: 'https://example.com/navigation',
    sortOrder: 3
  }
}

// 生命周期 - 加载数据
onMounted(() => {
  loadCarouselDetail()
})

/**
 * 加载轮播图详情数据
 */
const loadCarouselDetail = async () => {
  const id = route.params.id as string
  if (!id) {
    ElMessage.error('缺少轮播图ID参数')
    router.push('/content/carousel')
    return
  }

  loading.value = true
  
  try {
    const response = await carouselApi.getDetail(id)
    
    if (response.code === 200 && response.data) {
      const carouselData = response.data
      
      // 回填表单数据
        formData.title = carouselData.title
        formData.imageUrl = carouselData.imageUrl
        formData.linkUrl = carouselData.linkUrl || ''
        formData.isEnabled = carouselData.status === 1
        formData.sortOrder = carouselData.sort || 0
      
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '数据加载失败')
      router.push('/content/carousel')
    }
    
  } catch (error) {
    console.error('数据加载失败:', error)
    ElMessage.error('数据加载失败')
    router.push('/content/carousel')
  } finally {
    loading.value = false
  }
}

// 上传地址（直接使用Write API地址，避免代理冲突）
const uploadAction = ref('http://localhost:5049/api/fileupload/carousel/upload')

// 图片上传成功
const handleUploadSuccess = (response: any) => {
  // Element Plus的el-upload组件返回的响应结构处理
  // 后端API返回格式：{ code: 200, message: "图片上传成功", data: "完整图片URL" }
  
  let actualResponse = response;
  
  // 处理可能的嵌套结构
  if (response && response.response) {
    actualResponse = response.response;
  }
  
  // 检查响应状态码
  if (actualResponse && actualResponse.code === 200 && actualResponse.data) {
    // 直接使用后端返回的完整URL
    formData.imageUrl = actualResponse.data
    ElMessage.success(actualResponse.message || '图片上传成功')
  } else {
    // 处理错误情况
    const errorMsg = actualResponse?.message || response?.message || '图片上传失败'
    ElMessage.error(errorMsg)
    console.error('图片上传失败:', actualResponse)
  }
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 移除图片
const removeImage = () => {
  formData.imageUrl = ''
  ElMessage.info('图片已移除')
}

/**
 * 提交表单更新轮播图
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        const id = route.params.id as string
        
        // 构建更新数据
        const updateData = {
          id: parseInt(id),
          title: formData.title,
          imageUrl: formData.imageUrl,
          linkUrl: formData.linkUrl || '',
          status: formData.isEnabled ? 1 : 0, // 转换为枚举值：1=Active(上架)，0=Inactive(下架)
          sort: formData.sortOrder || 1
        }
        
        const response = await carouselApi.update(parseInt(id), updateData)
        
        if (response.code === 200) {
          ElMessage.success('轮播图更新成功')
          router.push('/content/carousel')
        } else {
          ElMessage.error(response.message || '更新失败')
        }
        
      } catch (error) {
        console.error('更新失败:', error)
        ElMessage.error('更新失败，请重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 取消操作
const handleCancel = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.carousel-edit {
  padding: 20px;
  
  .page-header {
    margin-bottom: 32px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    p {
      margin: 0;
      color: $text-color-regular;
      font-size: 14px;
    }
  }
  
  .form-container {
    background: white;
    border-radius: 8px;
    box-shadow: $box-shadow-base;
    padding: 40px;
    max-width: 800px;
    
    .carousel-form {
      .el-form-item {
        margin-bottom: 32px;
        
        .el-form-item__label {
          font-weight: 500;
          color: $text-color-primary;
          font-size: 14px;
        }
        
        .el-input {
          .el-input__wrapper {
            border-radius: 6px;
          }
        }
        
        .el-input-number {
          .el-input__wrapper {
            border-radius: 6px;
          }
          
          .el-input__inner {
            text-align: left;
          }
        }
      }
    }
    
    .upload-section {
      .image-uploader {
        .uploaded-container {
          position: relative;
          display: inline-block;
          
          .uploaded-image {
            width: 240px;
            height: 135px;
            object-fit: cover;
            border-radius: 8px;
            display: block;
            border: 1px solid $border-color-light;
          }
          
          .image-overlay {
            position: absolute;
            top: 8px;
            right: 8px;
            
            .delete-icon {
              width: 24px;
              height: 24px;
              background: rgba(0, 0, 0, 0.6);
              color: white;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              font-size: 14px;
              transition: background-color 0.3s;
              
              &:hover {
                background: rgba(0, 0, 0, 0.8);
              }
            }
          }
        }
        
        .upload-area {
          width: 240px;
          height: 135px;
          border: 2px dashed $border-color;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.3s;
          background-color: #fafbfc;
          
          &:hover {
            border-color: $primary-color;
            background-color: #f0f7ff;
          }
          
          .upload-icon {
            font-size: 36px;
            color: #c0c4cc;
          }
        }
      }
      
      .upload-hint {
        margin-top: 12px;
        font-size: 12px;
        color: $text-color-secondary;
        line-height: 1.4;
      }
    }
    
    .sort-section {
      .sort-hint {
        margin-top: 12px;
        font-size: 12px;
        color: $text-color-secondary;
        line-height: 1.4;
      }
    }
    
    .form-actions {
      margin-top: 48px;
      display: flex;
      justify-content: center;
      gap: 16px;
      
      .el-button {
        min-width: 100px;
        border-radius: 6px;
      }
    }
  }
}

// Element Plus 组件样式覆盖
:deep(.el-upload-dragger) {
  padding: 0;
  border: none;
  border-radius: 8px;
  
  &:hover {
    border-color: transparent;
  }
}

:deep(.el-switch) {
  .el-switch__core {
    border-radius: 20px;
  }
}

// Loading 样式
:deep(.el-loading-mask) {
  border-radius: 8px;
}
</style>